
package com.yunfei.api.user;
import cn.emay.util.SendMessageUtils;
import com.yunfei.api.user.contants.UserCenterContants;
import com.yunfei.api.user.param.AccountLoginForAdminParam;
import com.yunfei.api.user.param.UpdateUserInfoParam;
import com.yunfei.api.user.responseBody.LoginAndRegiterResult;
import com.yunfei.api.user.responseBody.LoginOutResult;
import com.yunfei.api.user.result.*;
import com.yunfei.api.user.valid.LoginForm;
import com.yunfei.api.user.valid.MobileForm;
import com.yunfei.api.user.valid.TokenForm;
import com.yunfei.bo.TPersonalUserBo;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.contants.ApplicationConstant;
import com.yunfei.contants.CodeMessageConstant;
import com.yunfei.contants.RedisConstants;
import com.yunfei.contants.TokenResult;
import com.yunfei.entity.TPersonalUserEntity;
import com.yunfei.enums.ResultStatus;
import com.yunfei.fegin.RedisFeignService;
import com.yunfei.mapper.aiiidb.GetStatusMapper;
import com.yunfei.mapper.aiiidb.TCrmUserMapper;
import com.yunfei.mapper.aiiidb.TPersonalUserMapper;
import com.yunfei.ribbon.RedisServiceRibbon;
import com.yunfei.service.RedisService;
import com.yunfei.service.ValidMobileAndCodeService;
import com.yunfei.utils.*;
import com.yunfei.utils.id.IdUtils;
import com.yunfei.utils.string.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data;

/**
 * @Description: 用户中心
 * @Author: zhengyunfei
 * @Date: 2018/6/15
 * @time:11:26
 */
@SuppressWarnings("ALL")
@Api(value = UserCenterContants.USER_CENTER_API_NAMESPACE,tags = UserCenterContants.USER_CENTER_API_NAMESPACE )
@RestController
@RequestMapping("/api/v2/user")
public class UserCenterApiController {
    @Autowired
    private TPersonalUserMapper tPersonalUserMapper;
    @Autowired
    private GetStatusMapper getStatusMapper;
    @Autowired
    private RedisFeignService redisFeignService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisServiceRibbon redisServiceRibbon;
    @Autowired
    private ValidMobileAndCodeService validMobileAndCodeService;
    @Autowired
    private TCrmUserMapper tCrmUserMapper;
    @Autowired
    private Environment env;


    /**
     * @Description:手机号加验证码登录
     * @Author: zhengyunfei
     * @Date: 2018/10/30
     * @time:9:13
     */
    @PostMapping(value="/login",produces = "application/json;charset=UTF-8")
    @ApiOperation(value =UserCenterContants.API_LOGIN_REGISTER,notes = UserCenterContants.AUTHOR_NOTE,position = 1,response = LoginAndRegiterResult.class)
    public Object login(@Valid LoginForm loginRequest, BindingResult bindingResult){
        ResultModel resultModel=new ResultModel();
        try{
            String mobile=loginRequest.getMobile();//手机号
            String vcode=loginRequest.getVcode();//验证码
            if(bindingResult.hasErrors()){
                if (validMobileAndCodeService.ValidMobileAndCode(bindingResult, resultModel)) return resultModel;
            }else{
                //参数校验成功
                boolean codeSuccess=false;
                //校验验证码是否正确
                String key=mobile+vcode;
                String isOpen= env.getProperty(CodeMessageConstant.MOBILE_CODE_COMMON_OPEN);
                if(isOpen.equals("true")){
                    if(vcode.equals(CodeMessageConstant.MOBILE_CODE_COMMON)){
                        codeSuccess=true;
                    }
                }
                if(redisService.exists(key)||codeSuccess){//验证码校验正确
                    //判断手机号码是否存在，存在的话更新登录次数和最近登录时间，不存在的话则注册用户
                    TPersonalUserBo personalUserBoParam=new TPersonalUserBo();
                    personalUserBoParam.setMobile(mobile);
                    personalUserBoParam.setUserType(UserCenterContants.USER_TYPE_01);//标识用户登录
                    int count=tPersonalUserMapper.count(personalUserBoParam);
                    if(count>0){
                        //再次登录，先删除原有token，防止 多点登录
                        List<TPersonalUserEntity> list= tPersonalUserMapper.findAllList(personalUserBoParam);
                        TPersonalUserEntity  tPersonalUserBo=list.get(0);
                        String userId="";
                        if(!StringUtil.isNullOrEmpty(tPersonalUserBo)){
                            userId=tPersonalUserBo.getUserId();
                            String lastLoginTimeStr=tPersonalUserBo.getLastLoginTime();
                            //删除原来的token
                            String oldKey=lastLoginTimeStr+userId;
                            String oldToken=TokenUtil.getInstance().getToken(userId,lastLoginTimeStr);
                            if(redisService.exists(oldToken)){
                                redisService.remove(oldToken);
                            }
                        }
                        //再更新登录次数和最近登录时间
                        TPersonalUserBo updateBo=new TPersonalUserBo();
                        String lastLoginTime= DateUtil.getDateNow();
                        updateBo.setLastLoginTime(lastLoginTime);
                        updateBo.setMobile(mobile);
                        tPersonalUserMapper.updateLoginCount(updateBo);
                        String newToken= TokenUtil.getInstance().getToken(userId,lastLoginTime);
                        redisService.set(newToken,newToken, RedisConstants.SESSION_EXPIRES_30, TimeUnit.DAYS);
                        TokenResult userInfoResult=new TokenResult();
                        userInfoResult.setToken(newToken);
                        resultModel.setData(userInfoResult);
                        resultModel.setCode(ResultStatus.SUCCESS.getCode());
                        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                    }else{
                        //首次登录
                        TPersonalUserBo registerBo=new TPersonalUserBo();
                        String userType= UserCenterContants.USER_TYPE_01;
                        String userId= IdUtils.getId();
                        registerBo.setMobile(mobile);
                        registerBo.setUserId(userId);
                        String lastLoginTime= DateUtil.getDateNow();
                        registerBo.setLastLoginTime(lastLoginTime);
                        registerBo.setUserType(userType);
                        registerBo.setPassword(Md5Util.string2MD5("111111"));
                        tPersonalUserMapper.add(registerBo);
                        //注册更改，返回token信息
                        String token=TokenUtil.getInstance().getToken(userId,lastLoginTime);
                        //存放token到redis缓存中，并设置有效期为30天
                        redisService.set(token,token, RedisConstants.SESSION_EXPIRES_30, TimeUnit.DAYS);
                        TokenResult userInfoResult=new TokenResult();
                        userInfoResult.setToken(token);
                        resultModel.setData(userInfoResult);
                        resultModel.setCode(ResultStatus.SUCCESS.getCode());
                        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                    }
                    //验证码使用后，移除缓存
                    redisService.remove(key);
                }else{
                    //验证码错误
                    resultModel.setCode(ResultStatus.CODE_ERROR.getCode());
                    resultModel.setMessage(ResultStatus.CODE_ERROR.getMessage());
                    return resultModel;
                }


            }
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }
    /**
     * @Description: 账号加密码登录
     * @Param:
     * @return:
     * @Author: zhengyunfei
     * @Date: 2019/1/3
     * @time:13:33
     */
    @RequestMapping(value =  "/loginForPassword", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ApiOperation(value =UserCenterContants.API_LOGIN_FOR_ACCOUNT_AND_PASSWORD,notes = UserCenterContants.AUTHOR_NOTE,position = 1,response = LoginAndRegiterResult.class)
    public Object add(@Valid AccountLoginForAdminParam accountLoginParam, BindingResult bindingResult) {
        ResultModel returnInfo=new ResultModel();
        String errorMsg="";
        if(bindingResult.hasErrors()){
            if (validMobileAndCodeService.ValidMobileAndPassword(bindingResult, returnInfo))
                return returnInfo;
        }else{
            try {
                String userName=accountLoginParam.getUserName();
                String passwordStr=accountLoginParam.getPassword();
                String userPwd= DESEncrypt.hsEncrypt(passwordStr);
                //调用存储过程,校验用户名和密码是否正确，并返回结果
                //  p_reasoncode = 0时  代表登录失败 错误信息在 p_reasoninfo展示
                //  p_reasoncode = 1时  代表登录成功 p_reasoninfo展示Y代表为客服部 展示N时代表非客服部
                //  p_emplname 登录成功 返回登录账号的中文名称
                String jdbcUrl=env.getProperty(ApplicationConstant.JDBC_URL);
                String driveClassName=env.getProperty(ApplicationConstant.driverClassName);
                String jdbcUserName=env.getProperty(ApplicationConstant.USERNAME);
                String jdbcPassword=env.getProperty(ApplicationConstant.PASSWORD);
                LoginAdminReturnResult returnResult=new Procedure().callProcedureForCheckLogin(jdbcUrl,driveClassName,jdbcUserName,jdbcPassword,userName,userPwd);
                if(!StringUtil.isNullOrEmpty(returnResult)){
                    int code=returnResult.getpReasonCode();
                    String message=returnResult.getpReasonInfo();
                    if(code==1){
                        //保存登录的账号
                        String crmLoginName=returnResult.getpEmplName();
                        System.out.println("登录成功=========="+returnResult.getpEmplName()+",info="+returnResult.getpReasonInfo()+",code="+returnResult.getpReasonCode());
                       // String userId=userName;
                        //根据crmLoginName查询userId userId获取待定
                       TPersonalUserBo tPersonalUserBoQueryParam=new TPersonalUserBo();
                        tPersonalUserBoQueryParam.setUserName(userName);
                        String userId=tPersonalUserMapper.getLiCaiShiUserId(tPersonalUserBoQueryParam);

                        String lastLoginTime= DateUtil.getDateNow();
                        String token=TokenUtil.getInstance().getToken(userId,lastLoginTime);
                        System.out.println("token==========================="+token);
                        //存放token到redis缓存中，并设置有效期为30天
                        redisService.set(token,token, RedisConstants.SESSION_EXPIRES_30, TimeUnit.DAYS);
                        System.out.println("从redis中获取到的刚刚保存的缓存信息是new======"+redisService.get(token));
                        TokenResult userInfoResult=new TokenResult();
                        userInfoResult.setToken(token);
                        returnInfo.setData(userInfoResult);
                        returnInfo.setCode(ResultStatus.SUCCESS.getCode());
                        returnInfo.setMessage(ResultStatus.SUCCESS.getMessage());

                    }else{
                        //账号或者密码错误
                        returnInfo.setData(returnResult);
                        returnInfo.setCode(-1);
                        returnInfo.setMessage(message);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        return returnInfo;
    }


    /**
     * @Description: 退出登录
     * @Author: zhengyunfei
     * @Date: 2018/10/30
     * @time:9:13
     */
    @PostMapping(value = "/loginout",produces = "application/json;charset=UTF-8")
    @ApiOperation(value =UserCenterContants.API_LOGIN_OUT,notes = UserCenterContants.AUTHOR_NOTE,position = 1,response = LoginOutResult.class)
    public Object loginout(@Valid TokenForm tokenForm, BindingResult bindingResult){
        ResultModel resultModel=new ResultModel();
        try{
            String token=tokenForm.getToken();//token
            if(bindingResult.hasErrors()){
                if (validMobileAndCodeService.ValidToken(bindingResult, resultModel)) return resultModel;
            }else{
                //参数校验成功
                if(redisService.exists(token)){
                    redisService.remove(token);
                    resultModel.setCode(ResultStatus.SUCCESS.getCode());
                    resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                }else{
                    resultModel.setCode(ResultStatus.TOKEN_ERROR.getCode());
                    resultModel.setMessage(ResultStatus.TOKEN_ERROR.getMessage());
                }

            }
        }catch (Exception e){
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }

    @PostMapping(value = "/getCode",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = UserCenterContants.API_GET_CODE,notes = UserCenterContants.AUTHOR_NOTE,position = 2,response = GetCodeResult.class)
    public ResultModel login(@Valid MobileForm loginRequest, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            String mobile=loginRequest.getMobile();//手机号
            if(bindingResult.hasErrors()){
                if (validMobileAndCodeService.ValidMobile(bindingResult, resultModel)) return resultModel;
            }else{
                //参数校验成功
                String vcode=  RandomStringUtils.randomNumeric(6);
                String key=mobile+vcode;
                String today=DateUtil.getToDay(DateUtil.YYYMMMDD);
                String sendCountKey="getCodeCountToday"+mobile+today;
                int sendCount=0;
                if(redisService.exists(sendCountKey)){
                    sendCount=Integer.parseInt(redisService.get(sendCountKey)+"");
                }
                if(sendCount>5){
                    resultModel.setCode(ResultStatus.AUTH_ERROR_24.getCode());
                    resultModel.setMessage(ResultStatus.AUTH_ERROR_24.getMessage());
                    return resultModel;
                }
                //存放该手机号码今天发送短信的次数到缓存中
                redisService.set(sendCountKey,sendCount++);
                String ip= IpUtils.getIp(request);
                String ipSendCountKey="getCodeCountIpToday"+mobile+ip;
                int ipSendCount=0;
                if(redisService.exists(ipSendCountKey)){
                    ipSendCount=Integer.parseInt(redisService.get(ipSendCountKey)+"");
                }
                if(ipSendCount>10){
                    resultModel.setCode(ResultStatus.AUTH_ERROR_24.getCode());
                    resultModel.setMessage(ResultStatus.AUTH_ERROR_24.getMessage());
                }

                redisServiceRibbon.set2(key,vcode,RedisConstants.SESSION_EXPIRES_SECONDS_60,TimeUnit.SECONDS);//将短信验证码保存到缓存中，并设置1分钟有效期
                resultModel.setCode(ResultStatus.CODE_SEND_SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.CODE_SEND_SUCCESS.getMessage());
                //发送短信
                //获取短信签名
                String signature=env.getProperty(CodeMessageConstant.SMS_SIGNATURE);
                String codeTemplate=env.getProperty(CodeMessageConstant.SMS_CODE_TEMPLATE);
                String isSend=env.getProperty(CodeMessageConstant.MOBILE_CODE_SEND_OPEN);
                String debug=env.getProperty(ApplicationConstant.DEBUG);
                if(ApplicationConstant.DEBUG_VALUE.equals(debug)){//生产环境
                    if("true".equals(isSend)){
                        //发送短信
                        SendMessageUtils.setSingleSms(signature+codeTemplate.replace(CodeMessageConstant.XX,vcode),mobile,false);
                    }
                }

                resultModel.setData(vcode);
                resultModel.setCode(ResultStatus.CODE_SEND_SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.CODE_SEND_SUCCESS.getMessage());

            }
        }catch (Exception e){
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }

    @PostMapping(value = "/getUserInfo",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = UserCenterContants.API_GET_TOKEN_INFO,notes =  UserCenterContants.AUTHOR_NOTE,position = 3,response = UserInfoResult.class)
    public ResultModel getUserInfo(@Valid TokenForm tokenRequest, BindingResult bindingResult){
        ResultModel resultModel=new ResultModel();
        try{
            String token=tokenRequest.getToken();//token原码
            System.out.println("token=================="+token);
            if(bindingResult.hasErrors()){
                List<ObjectError> list = bindingResult.getAllErrors();
                for (ObjectError error : list) {
                    resultModel.setCode(Integer.parseInt(error.getCode()));
                    resultModel.setMessage(error.getDefaultMessage());
                    return resultModel;
                }
            }else{
                //参数校验成功
                //校验验证码是否正确
                String key=token;
                boolean flag=redisService.exists(key);
                System.out.println("tokenflag============================================"+flag);
                if(flag){
                    //token有效
                    String userId=TokenUtil.getInstance().getUserId(token);
                    UserInfoResult userInfoResult=new UserInfoResult();
                    userInfoResult.setCustNo(userId);
                    TPersonalUserEntity tp=tPersonalUserMapper.findById(userId);
                    System.out.println("tp==============================="+tp);
                    if(!StringUtil.isNullOrEmpty(tp)){
                        String mobile=tp.getMobile();
                        userInfoResult.setNickName(tp.getUserName());//姓名
                        userInfoResult.setMobile(mobile);//手机号
                        userInfoResult.setIdentity(tp.getUserType());//用户类型
                        userInfoResult.setHeadIcon(tp.getIconUrl());//头像
                        userInfoResult.setRemark(tp.getRemark());
                        String userType=tp.getUserType();
                        System.out.println("userType==============================="+userType);
                        if(UserCenterContants.USER_TYPE_01.equals(userType)){
                            //客户的话，需要查询下面的
                            String cCustNo=tPersonalUserMapper.getCustNo(mobile);
                            if(!StringUtil.isNullOrEmpty(cCustNo)){
                                userInfoResult.setCustNo(cCustNo);
                                String custName=tCrmUserMapper.getCustName(cCustNo);
                                if(!StringUtil.isNullOrEmpty(custName)){
                                    userInfoResult.setCustName(custName);
                                }
                            }
                            //查询实名认证状态
                            Map<String,Object>  mobileMap=new HashMap<>();
                            mobileMap.put("mobile",tp.getMobile());
                            String smrzStatusName=getStatusMapper.getSmrzStatusName(mobileMap);
                            userInfoResult.setSmrzStatusName(smrzStatusName);
                            System.out.println("smrzStatus================"+userInfoResult.getSmrzStatus());
                            int  smrzStatus=0;
                            if("去认证".equals(smrzStatusName)){
                                smrzStatus=0;
                            }
                            if("待审核".equals(smrzStatusName)){
                                smrzStatus=1;
                            }
                            if("审核驳回".equals(smrzStatusName)){
                                smrzStatus=2;
                            }
                            if("查看".equals(smrzStatusName)){
                                smrzStatus=3;
                            }
                            userInfoResult.setSmrzStatus(smrzStatus);
                            //风险承若涵状态
                            Map<String,Object> userIdMap=new HashMap<>();
                            userIdMap.put("userId",userId);
                            String feiXianTouZiChengRuoHanStatus= getStatusMapper.getChengRuoHanStatus(userIdMap);
                            userInfoResult.setFeiXianTouZiChengRuoHanStatus(feiXianTouZiChengRuoHanStatus);
                            //风险问卷调查
                            int getFengXianWenJuanDiaoChaStatus=getStatusMapper.getFengXianWenJuanDiaoChaStatus(userIdMap);
                            userInfoResult.setFengXianWenJuanStatus(getFengXianWenJuanDiaoChaStatus);
                        }
                        resultModel.setData(userInfoResult);
                        resultModel.setCode(ResultStatus.SUCCESS.getCode());
                        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                    }

                }else{
                    resultModel.setCode(ResultStatus.TOKEN_ERROR.getCode());
                    resultModel.setMessage(ResultStatus.TOKEN_ERROR.getMessage());
                    return resultModel;
                }


            }
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }
   /**
   * @Description: 更新用户基本信息
   * @Param: [tokenRequest, bindingResult]
   * @return: com.yunfei.bo.result.ResultModel
   * @Author: zhengyunfei
   * @Date: 2019/4/3
   * @time:9:49
   */
    @PostMapping(value = "/updateUserInfo",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = UserCenterContants.API_UPDATE_TOKEN_INFO,notes =  UserCenterContants.AUTHOR_NOTE,position = 3,response = UserInfoResult.class)
    public ResultModel updateUserInfo(@Valid UpdateUserInfoParam userInfoParam, BindingResult bindingResult){
        ResultModel resultModel=new ResultModel();
        try{
            String token=userInfoParam.getToken();//token原码
            if(bindingResult.hasErrors()){
                List<ObjectError> list = bindingResult.getAllErrors();
                for (ObjectError error : list) {
                    resultModel.setCode(ResultStatus.PARAM_ERROR.getCode());
                    resultModel.setMessage(error.getDefaultMessage());
                    return resultModel;
                }
            }else{
                //参数校验成功
                //校验验证码是否正确
                String key=token;
                boolean flag=redisService.exists(key);
                if(flag){
                    //token有效
                    String userId=TokenUtil.getInstance().getUserId(token);
                    TPersonalUserBo updateParm=new TPersonalUserBo();
                    updateParm.setUserId(userId);
                    updateParm.setMobile(userInfoParam.getMobile());
                    updateParm.setUserName(userInfoParam.getNickName());
                    updateParm.setRemark(userInfoParam.getRemark());
                    updateParm.setLinkTel(userInfoParam.getMobile());
                    String headIcon=userInfoParam.getHeadIcon();
                    if(headIcon.contains("\"")){
                        headIcon=headIcon.replaceAll("\"","");
                    }
                    updateParm.setIconUrl(headIcon);
                    tPersonalUserMapper.update(updateParm);
                   // resultModel.setData();
                    resultModel.setCode(ResultStatus.SUCCESS.getCode());
                    resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                }else{
                    resultModel.setCode(ResultStatus.TOKEN_ERROR.getCode());
                    resultModel.setMessage(ResultStatus.TOKEN_ERROR.getMessage());
                    return resultModel;
                }


            }
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }

    /**
     * @Description: 头像图片上传
     * @Author: zhengyunfei
     * @Date: 2019/1/25
     * @time:10:32
     */
    @RequestMapping(value = "/uploadHeadIcon",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ApiOperation(value = "头像上传",notes = "头像上传与修改",position = 1,response = UploadHeadIconResult.class)
    @ResponseBody
    public Object saveCardPic(HttpServletRequest request, HttpServletResponse response, String token){
        String userId= TokenUtil.getInstance().getUserId(token);
        ResultModel resultModel=new ResultModel();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) + "files/";
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile1 = multipartHttpServletRequest.getFile("file");
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            if (!imgFile1.isEmpty()) {
                //获取前端传来的文件名
                String fileName = imgFile1.getOriginalFilename();
                // 设置存放图片文件的路径
                String today= DateUtil.getToDay("yyyyMMdd");
                try {
                    TPersonalUserEntity userEntity=new TPersonalUserEntity();
                    userEntity.setUserId(userId);
                    String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                    String filePath=uploadPath+"headIcon/"+today+"/"+userId+"."+fileExt;
                    try {
                        //利用文件流保存文件
                        File saveFile= new File(filePath);
                        File parentFile=saveFile.getParentFile();
                        if(!parentFile.exists()&&!parentFile.isDirectory()){
                            parentFile.mkdirs();
                        }
                        if(!saveFile.exists())
                        {
                            try {
                                saveFile.createNewFile();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        imgFile1.transferTo(saveFile);
                        System.out.println("用户头像上传路径："+filePath);
                        String fileUrl = imageDomain  + "headIcon/" +today+"/"+userId+"."+fileExt;
                       // userEntity.setIconUrl(fileUrl);
                       // tPersonalUserMapper.update(userEntity);
                        System.out.println("用户头像访问地址=========="+fileUrl);
                        resultModel.setData(fileUrl);
                        return fileUrl;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {

                }

            }


        }
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }

    @PostMapping(value = "/getShuangLuUserInfo",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = UserCenterContants.API_GET_TOKEN_INFO,notes =  UserCenterContants.AUTHOR_NOTE,position = 3,response = UserInfoResult.class)
    public ResultModel getShuangLuUserInfo(@Valid TokenForm tokenRequest, BindingResult bindingResult){
        ResultModel resultModel=new ResultModel();
        try{
            String token=tokenRequest.getToken();//token原码
            if(bindingResult.hasErrors()){
                List<ObjectError> list = bindingResult.getAllErrors();
                for (ObjectError error : list) {
                    resultModel.setCode(Integer.parseInt(error.getCode()));
                    resultModel.setMessage(error.getDefaultMessage());
                    return resultModel;
                }
            }else{
                //参数校验成功
                //校验验证码是否正确
                String key=token;
                boolean flag=redisService.exists(key);
                if(flag){
                    //token有效
                    String userId=TokenUtil.getInstance().getUserId(token);
                    ShuangLuUserInfoResult userInfoResult=new ShuangLuUserInfoResult();
                    userInfoResult.setCustNo(userId);
                    TPersonalUserEntity tp=tPersonalUserMapper.findById(userId);
                    if(!StringUtil.isNullOrEmpty(tp)){
                        String cCustNo=tPersonalUserMapper.getCustNo(tp.getMobile());
                        if(!StringUtil.isNullOrEmpty(cCustNo)){
                            userInfoResult.setCustNo(cCustNo);
                        }
                        userInfoResult.setNickName(tp.getUserName());//姓名
                        userInfoResult.setMobile(tp.getMobile());//手机号
                        userInfoResult.setIdentity(tp.getUserType());//用户类型
                        userInfoResult.setHeadIcon(tp.getIconUrl());//头像
                        userInfoResult.setRemark(tp.getRemark());
                        String userType=tp.getUserType();
                        if(UserCenterContants.USER_TYPE_01.equals(userType)){
                            //查询其客户经理对应的客户号
                            String liCaishiCustNo= tPersonalUserMapper.getLiCaiShiCustNo(cCustNo);
                            if(!StringUtil.isNullOrEmpty(liCaishiCustNo)){
                                userInfoResult.setLiCaiShiCustNo(liCaishiCustNo);
                            }
                        }
                        resultModel.setData(userInfoResult);
                        resultModel.setCode(ResultStatus.SUCCESS.getCode());
                        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                    }

                }else{
                    resultModel.setCode(ResultStatus.TOKEN_ERROR.getCode());
                    resultModel.setMessage(ResultStatus.TOKEN_ERROR.getMessage());
                    return resultModel;
                }


            }
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }


    @PostMapping(value = "/getDomain",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = UserCenterContants.GET_DOMAIN,notes =  UserCenterContants.GET_DOMAIN,position = 3,response = ResultModel.class)
    public ResultModel getDomain(){
        ResultModel resultModel=new ResultModel();
        try{
           String domain=env.getProperty(ApplicationConstant.DOMAIN);
            resultModel.setData(domain);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }

        return resultModel;
    }
}
